package com.topvision.camerasdk.video;


import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.topvision.camerasdk.R;
import com.topvision.camerasdk.album.PhotoMenuActivity;
import com.topvision.camerasdk.album.adapter.PhotoGridAdapter;
import com.topvision.commomsdk.commom.Album;
import com.topvision.camerasdk.video.util.VideoConstant;
import com.topvision.commomsdk.TouchInterface;
import com.topvision.voicesdk.BaseVoiceActivity;
import com.topvision.voicesdk.CommonVoice;
import com.topvision.voicesdk.VoiceInterface;

import java.io.File;
import java.util.ArrayList;


public class PlayVideoActivity extends BaseVoiceActivity implements TouchInterface, VoiceInterface {
    public static final String ALBUM_KEY = "album_key";
    //快进\快退 变化常量
    public  final int VIDEO_SEEK_THRESHOLD = 3000;
    private VideoView mVideoView;
    private String videoPath;
    //暂停的时间
    private int currentVideoPosition;
    //所有视频对象
    private ArrayList<Album> pageList;
    //点击是第几个
    private int positionTag;
    private Album album;
    public static PlayVideoActivity playVideoActivity = null;
    private boolean VoiceServiceIsRun;
    //是否轮播标示
    boolean video_Carousel;

    MediaController con;
    Uri uri;
    AudioManager mAudioManager;
    //视频的时长
    int videoTime = 0;
    RelativeLayout circleProgressRel;
    private static final int NEXT_VIDEO = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case NEXT_VIDEO:
                    nextVideo();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置成全屏模式
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.activity_play_video);
        playVideoActivity = this;
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        initView();
        initDate();

    }


    private void initView() {
        mVideoView = (VideoView) findViewById(R.id.myVideoView);
        circleProgressRel = (RelativeLayout) findViewById(R.id.circle_progress_rel);
    }

    private void initDate() {
        videoPath = getIntent().getStringExtra(VideoConstant.PLAY_VIDEO_PATH);
        positionTag = getIntent().getIntExtra(PhotoGridAdapter.CURRENT_POSITON, 0);
        pageList = getIntent().getParcelableArrayListExtra(VideoConstant.ALBUM_KEY);
        //是否轮播参数
        video_Carousel = getIntent().getBooleanExtra(VideoConstant.PLAY_VIDEO_CAROUSEL, false);
        //播放视频
        palyVideo();
        //添加视频播放结束回调
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                //是否轮播参数
                if (video_Carousel) {
                    circleProgressRel.setVisibility(View.VISIBLE);
                    handler.sendEmptyMessageDelayed(NEXT_VIDEO, 500);
                }
            }
        });

        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //报错直接退出，重新进入
                setResult(RESULT_OK);
                finish();
                return true;
            }
        });
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){

            @Override
            public void onPrepared(MediaPlayer mp) {
                circleProgressRel.setVisibility(View.GONE);
                videoTime = mVideoView.getDuration();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTouchInterfaceListener(this);
        setVoiceInterfaceListener(this);

        mVideoView.seekTo(currentVideoPosition);
        mVideoView.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        setTouchInterfaceListener(null);
        setVoiceInterfaceListener(null);
        if (mVideoView != null && mVideoView.isPlaying()) {
            //记录当前视频播放位置 暂停播放
            mVideoView.pause();
            currentVideoPosition = mVideoView.getCurrentPosition();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁时 把视频记录清0
        currentVideoPosition = 0;
        videoTime = 0;
        //释放资源
        if (mVideoView != null) {
            mVideoView.stopPlayback();
            mVideoView = null;
        }

    }


    @Override
    public void doForwardTouch() {
        if(mVideoView!=null){
            int seekToPosition =  mVideoView.getCurrentPosition()+VIDEO_SEEK_THRESHOLD;
            currentVideoPosition =  seekToPosition>videoTime?videoTime:seekToPosition;
            mVideoView.seekTo(currentVideoPosition);
            Log.e("currentVideoPosition", currentVideoPosition + "");
        }

    }

    @Override
    public void doBackwardTouch() {
        if(mVideoView!=null){
            int seekToPosition =  mVideoView.getCurrentPosition()-VIDEO_SEEK_THRESHOLD;
            currentVideoPosition =  seekToPosition>0?seekToPosition:0;
            mVideoView.seekTo(currentVideoPosition);
            Log.e("currentVideoPosition",currentVideoPosition+"");
        }
    }

    @Override
    public void doClickTouch() {
        choose();

    }

    @Override
    public void doDoubleTouch() {

    }

    private void choose() {

        showPhotoMenu();
       /* if (mVideoView.isPlaying()) {
            mVideoView.pause();
            showPhotoMenu();
        } else {
            continuePlayVideo();
        }*/

    }

    /**
     * 显示视频菜单列表
     *
     * @author jack
     * create at 2016/11/23 16:13
     */
    private void showPhotoMenu() {
        Intent intent = new Intent(this, PhotoMenuActivity.class);
        //获取当前视频信息
        album = pageList.get(positionTag);
        intent.putExtra(ALBUM_KEY, album);
        startActivity(intent);
    }


    @Override
    public void dealWithVoice(String voiceData) {
        if (voiceData.equals(CommonVoice.VOICE_ZH_PAUSE) || voiceData.equalsIgnoreCase(CommonVoice.VOICE_US_PAUSE)) {
            pauseVideo();
        } else if (voiceData.equals(CommonVoice.VOICE_ZH_DOWN) || voiceData.equalsIgnoreCase(CommonVoice.VOICE_US_DOWN)) {
            nextVideo();
        } else if (voiceData.equals(CommonVoice.VOICE_ZH_UP) || voiceData.equalsIgnoreCase(CommonVoice.VOICE_US_UP)) {
            lastVideo();
        } else if (voiceData.equals(CommonVoice.VOICE_ZH_KEEP_ON) || voiceData.equalsIgnoreCase(CommonVoice.VOICE_US_KEEP_ON)) {
            continuePlayVideo();
        } else if (voiceData.equals(CommonVoice.VOICE_ZH_BACK) || voiceData.equalsIgnoreCase(CommonVoice.VOICE_US_BACK)) {
            //释放资源
            mVideoView.stopPlayback();
            this.finish();
        } else if (voiceData.equals(CommonVoice.VOICE_ZH_MENU) || voiceData.equalsIgnoreCase(CommonVoice.VOICE_US_MENU)) {
            choose();
        }
    }


    //播放视频
    public void palyVideo() {
        //在初始化以及上 、下一个视频切换时把记录清0
        currentVideoPosition = 0;
        videoPath = pageList.get(positionTag).getPath();
        if (!videoPath.equals("") && videoPath != null) {
            File videoFile = new File(videoPath);
            if(videoFile.exists() && videoFile.length()>0){
                checkBlueEar();
                uri = Uri.parse(videoPath);
                //视频路径
                mVideoView.setVideoURI(uri);
                //使用这种方式创建MediaController将不会显示“快进”和“快退”两个按钮
                con = new MediaController(this, false);
                con.setVisibility(View.INVISIBLE);
                //设置video与con关联
                mVideoView.setMediaController(con);
                mVideoView.requestFocus();
                mVideoView.start();
            }else{
                //AndroidUtils.showTips(this,getString(R.string.video_source_error));
                finish();
            }

        } else {
            // AndroidUtils.showTips(this, getString(R.string.video_source_error));
            finish();
        }
    }

    //视频暂停
    public void pauseVideo() {
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                //记录当前视频播放位置
                mVideoView.pause();
                currentVideoPosition = mVideoView.getCurrentPosition();
            }
        }
    }

    //继续播放视频
    public void continuePlayVideo() {
        //重新打开页面时从记录的时间开始播放视频
        if (currentVideoPosition != 0 && mVideoView != null) {
            mVideoView.seekTo(currentVideoPosition);
            mVideoView.start();
        }
    }

    //下一个视频播放
    public void nextVideo() {
        if (positionTag < pageList.size() - 1) {
            positionTag = positionTag + 1;
            palyVideo();
        } else {
            positionTag = 0;
            palyVideo();
//            //释放资源
//            mVideoView.stopPlayback();
//            this.finish();

        }
    }

    //上一个视频
    public void lastVideo() {
        if (positionTag > 0 && positionTag < pageList.size()) {
            positionTag = positionTag - 1;
            palyVideo();
        } else {
            positionTag = 0;
            palyVideo();
//            //释放资源
//            mVideoView.stopPlayback();
//            this.finish();
        }
    }


    private void checkBlueEar() {
        try {
            if (!mAudioManager.isBluetoothA2dpOn())
                mAudioManager.setBluetoothA2dpOn(true); // 如果A2DP没建立，则建立A2DP连接
            mAudioManager.stopBluetoothSco();// 如果SCO没有断开，由于SCO优先级高于A2DP，A2DP可能无声音
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            mAudioManager.setStreamSolo(AudioManager.STREAM_MUSIC, true);
            // 让声音路由到蓝牙A2DP。此方法虽已弃用，但就它比较直接、好用。
            mAudioManager.setRouting(AudioManager.MODE_NORMAL,
                    AudioManager.ROUTE_BLUETOOTH_A2DP,
                    AudioManager.ROUTE_BLUETOOTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void cancelBlueEar() {
//        mAudioManager.setStreamSolo(AudioManager.STREAM_MUSIC, false);
//        mAudioManager.setStreamSolo(AudioManager.MODE_NORMAL, true);
    }


}
